class ReportRequest < ActiveRecord::Base
  
  has_many :report_responses

  belongs_to :requestor, :class_name => 'User'
  belongs_to :report, :class_name => 'Report'
  
  validates_presence_of :title, :description, :message, :period_start, :period_end, :due_date
  validates_length_of :title, :maximum  => 200

  #return the name of the report + the report period
  def title_and_period
    month_map={1 => "January", 6 => "June", 7=> "July", 12 => "December"}
    result =_(self.title)+ "#{month_map[self.period_start.month]}-#{month_map[self.period_end.month]} #{self.period_start.year}"
    return result
  end

  def strategy_responses
    report_responses.select{|rr| rr.owner_role.is_strategy_coordinator}
  end
  
  def strategy_responses_by_country
    res = {}
    strategy_responses.each do |rr|
      countries_from_role = rr.owner_role.users.map {|u| u.country}
      countries_from_role.each do |country| 
        if res[country].nil?
          res[country] = []
        end
        res[country] << rr
      end
    end
    res
  end
  
  def cc_responses_by_country
    res = report_responses.select {|rr| rr.owner_role.is_country_coordinator}
    res.group_by {|rr| rr.owner_role.country}
  end
  
  def xb_responses_by_country
    res = report_responses.select {|rr| rr.owner_role.is_cross_border}
    res.group_by {|rr| rr.owner_role.site.country}
  end
  
  def get_responses_grouped_by_xb
    # Load all responses for Site coordinator
    site_responses = report_responses.select { |response| response.owner_role.is_cross_border }
    # Group them by CrossBorder
    site_responses.group_by { |response| response.owner_role.site.cross_borders.min {|a,b| a.number <=> b.number} }
  end
  
   def get_xb_responses_grouped_by_site
    # Load all responses for Site coordinator
    site_responses = report_responses.select { |response| response.owner_role.is_cross_border }
    site_responses.group_by { |response| response.owner_role.site }
  end
  
  # Returns true if all report responses are submitted
  def all_submitted
    self.report_responses.map(&:is_submitted).inject(true) {|total, value| total and value}
  end
  
  # Return the current report request, that is the latest created
  def self.current
    self.find(:first, :order => 'created_at desc')
  end
  
  # Returns all the completed ReportRequest
  # A ReportRequest is completed when all of its ReportResponses are submitted (is_submitted = true)
  def self.completed
    self.find_by_sql("SELECT * FROM report_requests as repreq 
                      WHERE NOT EXISTS (SELECT 0 FROM report_responses as represp
                                       WHERE repreq.id = represp.report_request_id 
                                       AND represp.is_submitted = 0)")
  end
  
  # Returns all the pending ReportRequest
  # A ReportRequest is pending when at least one of its ReportResponses isnt submitted (is_submitted = false)
  def self.pending
    self.find_by_sql("SELECT * FROM report_requests as repreq 
                      WHERE EXISTS (SELECT 0 FROM report_responses as represp
                                    WHERE repreq.id = represp.report_request_id 
                                    AND represp.is_submitted = 0)")
  end
  
  # Return the previous completed ReportRequest
  def previous_request
    self.class.find_by_sql(["SELECT * FROM report_requests as repreq 
                             WHERE repreq.id < ? 
                             AND NOT EXISTS (SELECT 0 FROM report_responses as represp
                                             WHERE repreq.id = represp.report_request_id 
                                             AND represp.is_submitted = 0) 
                             ORDER BY repreq.id DESC 
                             LIMIT 1", self.id]).first
  end
  
  # Return the next completed ReportRequest
  def next_request
    self.class.find_by_sql(["SELECT * FROM report_requests as repreq 
                             WHERE repreq.id > ? 
                             AND NOT EXISTS (SELECT 0 FROM report_responses as represp
                                             WHERE repreq.id = represp.report_request_id 
                                             AND represp.is_submitted = 0) 
                             ORDER BY repreq.id ASC 
                             LIMIT 1", self.id]).first
  end
  
end
